#include "quizmain.h"
#include <QFile>
#include <QTime>
#include <QTimer>

QuizMain::QuizMain(ChatterBoxServer *server, int helpT, int hlp) : chatSrv(server)
{
    QTime time = QTime::currentTime();
    qsrand((uint)time.msec());
    loadQuestionsList();

    timer = new QTimer();
    connect(timer, SIGNAL(timeout()), this, SLOT(Checker()));

    hintcount = 0;
    hlpT = helpT;
    maxhlp = hlp;
    changing = false;
    userSrv = chatSrv->getUserSrv();

    askQuestion();
}

void QuizMain::askQuestion()
{
    timer->start(hlpT);

    if (askedQuestions.size() == 50)
        askedQuestions.clear();

    int randomnr = 0;
    if (!questions.isEmpty())
    {
        hintcount = 0;
        randomnr = qrand() % questions.size();

        while (askedQuestions.contains(randomnr))
            randomnr = qrand() % questions.size();

        currQuestion = questions[randomnr];
        askedQuestions.append(randomnr);
        displayCurrQuestion();
        changing = false;
    }
    else
        qDebug() << "No questions found.";
}

bool QuizMain::checkAnswer(QString name, QString answer)
{
    if (changing)
        return false;

    if (currQuestion.answer.toLower() == answer.toLower())
    {
        chatSrv->sendText(name + " answer is correct.");
        return true;
    }
    else
        return false;
}

void QuizMain::rewardUser(QString name)
{
    if (userSrv->SQLuserExist(name))
        userSrv->SQLaddScore(name, 1);
    else
        userSrv->SQLaddUser(name, 1);

    giveHint(currQuestion.answer.size());
    chatSrv->sendText(name + " Score(" + QString::number(userSrv->SQLgetScore(name)) + ")");
    changing = true;
    chatSrv->sendUserList();
    QTimer::singleShot( 3000, this , SLOT(askQuestion()));
}

void QuizMain::loadQuestionsList()
{
    questionsList temp;
    int qnr = 1;
    QString tempstr;
    QStringList tbr;
    QFile f("pataisyti.txt");
    if (!f.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "Failed at reading FILE";
        return;
    }

    QTextStream strm(&f);
    while (!strm.atEnd())
    {
        tempstr = strm.readLine();
        tbr = tempstr.split('*',QString::SkipEmptyParts);
        if (tbr.size() == 2)
        {
            temp.nr = qnr++;
            temp.question = tbr[0].trimmed();
            temp.answer = tbr[1].trimmed();
        }
        else
        {
            qDebug() << "Failed at reading LINE: " << qnr;
            continue;
        }

        questions.append(temp);
    }

    qDebug() << "Loaded " << questions.size() << " questions.";
    f.close();
}

void QuizMain::giveHint(int n)
{
    if (currQuestion.answer.size() < n)
        n = currQuestion.answer.size();
    QString s = currQuestion.answer;
    s.replace(QRegExp("\\w"), "*");

    for (int i = 0; i < n; i++)
        s[i] = currQuestion.answer[i];

    if (currQuestion.answer.size() == n)
        chatSrv->sendHint(s,hintcount,true);
    else
        chatSrv->sendHint(s,hintcount);
}

void QuizMain::displayCurrQuestion()
{
    //qDebug() << currQuestion.question;
    chatSrv->sendQuestion(currQuestion.nr, currQuestion.question);
    giveHint(hintcount);
}

void QuizMain::Checker()
{
    if (changing)
        return;

    hintcount++;

    if (hintcount > maxhlp)
    {
        hintcount = 0;
        //chatSrv->sendText(QString("Next question.").toUtf8());
        giveHint(currQuestion.answer.size());
        changing = true;
        QTimer::singleShot( 1000, this , SLOT(askQuestion()));
    }
    else
        giveHint(hintcount);
}

int QuizMain::getCurrQuestionID()
{
    return currQuestion.nr;
}

QString QuizMain::getCurrQuestion()
{
    return currQuestion.question;
}

void QuizMain::addQuestion(QString quest, QString answer)
{
    QFile file("newQuests.txt");
    if (!file.open(QIODevice::Append | QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream out(&file);
    out << quest << '*' << answer  << endl;

    file.close();
}
